package cn.readjava.controller;

import cn.readjava.bean.User;
import cn.readjava.constant.ShiroConstant;
import cn.readjava.service.UserService;
import cn.readjava.util.ResponseResult;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import java.sql.Timestamp;

@Controller
public class RegisterController {

    @Resource
    private UserService userService;

    @GetMapping("/register")
    public String register() {
        return "register";
    }

    @PostMapping("/register")
    public String register(User user, Model model) {
        model.addAttribute("user", user); // 回显
        User replyName = userService.findByUserName(user.getUserName());
        if (replyName != null) {
            model.addAttribute("result", new ResponseResult(100, "注册失败，该用户名已经被注册"));
            return "register";
        }
        User replyEmail = userService.findByUserEmail(user.getUserEmail());
        if (replyEmail != null) {
            model.addAttribute("result", new ResponseResult(100, "注册失败，该邮箱已经被注册"));
            return "register";
        }

        // 更新用户
        user.setUserState(0);
        user.setRegisterTime(new Timestamp(System.currentTimeMillis()));
        Md5Hash md5Pwd = new Md5Hash(user.getUserPassword(), user.getUserEmail() + ShiroConstant.SALT, ShiroConstant.HASHITERATIONS);
        user.setUserPassword(md5Pwd.toString());
        User u = userService.save(user);

        if (u != null) {
            model.addAttribute("result", new ResponseResult(200, "注册成功！用户名：" + u.getUserName() + "，登录邮箱：" + u.getUserEmail()));
            return "register";
        }
        model.addAttribute("result", new ResponseResult(100, "注册失败，请检查输入的信息是否合法"));
        return "register";
    }
}
